package com.bodacn.keypoint;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.view.View.GONE;
import static com.bodacn.keypoint.MainApplication.CSP_URL;
import static java.lang.String.valueOf;

public class AffirmDeActivity extends AppCompatActivity implements View.OnClickListener {
    public static final int MSG_GetProcOver = 1001;
    public static final int MSG_ERRMSG = 1002;
    public static final int MSG_SaveTransOver = 1003;
    public static final int MSG_GETDEPART=1005;

    //全局变量
    String SaveFilePath="",SaveDBFolder="/DB";
    public static final String DB_Name ="bdmes.db";
    SQLiteDatabase mainDB;

    //全局提示;
    Toast curToast;
    private ProgressDialog waitDialog = null;
    //布局元素;
    ListView procList;
    TextView view_rtpStyleNoText,view_styleNoText,view_styleSortText;
    TextView view_empNoText,view_empNameText,view_workNameText,view_workNoText;
    TextView text_SAMValue,text_TargetValue,text_RptValue,text_NotNormal,text_WorkName;
    EditText view_numEdit,edit_debug;
    Button view_oneBtn,view_twoBtn,view_threeBtn,view_fourBtn,view_fiveBtn,
            view_sixBtn,view_sevenBtn,view_eightBtn,view_nineBtn,view_zeroBtn,
            view_pointBtn,view_delBtn,view_clrBtn;

    //全局变量
    String curLoginUserNo,curLoginUser,serviceUrl="",curDepartNo="",curDepart="",
            curKeyID="",curOrderNo ="",  curRptStyleNo ="",curStyleNo ="",curStyleSort="",curFactory="";//操作员所属部门等信息;
    String CPUID="",curServiceUrl="",curServiceDir="",WorkSection="SEW",AllowAffirm="",AllowUnAffirm="";
    boolean overWriteSign,dataEditSign=false;
    //当前选中的内容;
    private int selRowIndex;//当前选中的行;
    private JSONArray procJSONArray,resultJson;
    float reservedprice=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //启动Activity
        setContentView(R.layout.activity_affirmde);
        hideBottomUIMenu();

        //创建对话框，
        waitDialog=new ProgressDialog(this);
        waitDialog.setTitle("请稍等");
        waitDialog.setIndeterminate(true);
        //获取登陆参数
        Bundle paramBundle = this.getIntent().getExtras();
        curLoginUserNo=paramBundle.getString("LoginUserNo");
        curLoginUser=paramBundle.getString("LoginUser");
        curDepartNo=paramBundle.getString("CurDepartNo");
        curDepart=paramBundle.getString("CurDepart");
        curFactory=paramBundle.getString("CurFactory");
        curOrderNo=paramBundle.getString("CurOrderNo");
        curRptStyleNo=paramBundle.getString("CurRptStyleNo");
        curStyleNo=paramBundle.getString("CurStyleNo");
        curStyleSort=paramBundle.getString("CurStyleSort");
        curKeyID=paramBundle.getString("CurKeyID");
        curServiceUrl=paramBundle.getString("ServiceUrl");
        curServiceDir=paramBundle.getString("ServiceDir");
        WorkSection=paramBundle.getString("WorkSection","SEW");
        AllowAffirm=paramBundle.getString("AllowAffirm","N");
        AllowUnAffirm=paramBundle.getString("AllowUnAffirm","N");
        reservedprice=paramBundle.getFloat("reservedprice",0);
        CPUID=paramBundle.getString("CPUID");
        System.out.println(paramBundle);
        //初始化按键，并将页面加载到fragment列表中;
        InitView();
        //打开或创建数据库文件;
        mainDB = openOrCreateDatabase(DB_Name, this.MODE_PRIVATE, null);
        findViewById(R.id.btn_viewRefresh).postDelayed(new Runnable() {
            public void run() {
                refreshProcListFromCSP(curDepartNo,curKeyID,curOrderNo,curRptStyleNo,curStyleNo,curStyleSort,curLoginUserNo);
            }
        }, 500);
    }



    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }


    // /判断外部存储是否可读写
    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }

    private void InitView() {
        //表格
        procList =(ListView)findViewById(R.id.procList);
        procList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                view.setSelected(true);
                //置选择制单信息;
                try {
                    selRowIndex=position;
                    view_workNoText.setText(procJSONArray.getJSONObject(position).getString("WorkNo"));
                    view_workNameText.setText(procJSONArray.getJSONObject(position).getString("WorkName"));
                    view_numEdit.setText(procJSONArray.getJSONObject(position).getString("RptValue"));
                    overWriteSign=true;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        System.out.println("ViewFragment..............................3");
        findViewById(R.id. btn_viewRefresh).setOnClickListener(this);
        findViewById(R.id.btn_saveData).setOnClickListener(this);
        findViewById(R.id.btn_affirmData).setOnClickListener(this);
        findViewById(R.id.btn_checkData).setOnClickListener(this);
        if (AllowAffirm.equals("N")) {
            findViewById(R.id.btn_saveData).setVisibility(GONE);
            findViewById(R.id.btn_affirmData).setVisibility(GONE);
            findViewById(R.id.btn_checkData).setVisibility(GONE);
            findViewById(R.id.linearEditNum).setVisibility(GONE);
        } else{
            findViewById(R.id.btn_affirmData).setVisibility(View.VISIBLE);
            findViewById(R.id.btn_saveData).setVisibility(View.VISIBLE);
            findViewById(R.id.btn_checkData).setVisibility(View.VISIBLE);
            findViewById(R.id.linearEditNum).setVisibility(View.VISIBLE);
        }
        //界面显示
        view_rtpStyleNoText=(TextView)findViewById(R.id.view_rtpStyleNoText);
        view_styleNoText=(TextView)findViewById(R.id.view_styleNoText);
        view_styleSortText=(TextView)findViewById(R.id.view_styleSortText);
        view_empNoText=(TextView)findViewById(R.id.view_empNoText);
        view_empNameText=(TextView)findViewById(R.id.view_empNameText);
        view_workNoText=(TextView)findViewById(R.id.view_workNoText);
        view_workNameText=(TextView)findViewById(R.id.view_workNameText);
        view_numEdit=(EditText)findViewById(R.id.view_numEdit);
        view_numEdit.setInputType(InputType.TYPE_NULL);
        edit_debug=(EditText)findViewById(R.id.edit_debug);
        text_SAMValue=findViewById(R.id.text_SAMValue);
        text_TargetValue=findViewById(R.id.text_TargetValue);
        text_RptValue=findViewById(R.id.text_RptValue);
        text_NotNormal=findViewById(R.id.text_NotNormal);
        text_WorkName=findViewById(R.id.text_WorkName);
        System.out.println("ViewFragment..............................4");
        //界面按键
        view_oneBtn=(Button)findViewById(R.id.view_oneBtn);
        view_oneBtn.setOnClickListener(this);
        view_twoBtn=(Button)findViewById(R.id.view_twoBtn);
        view_twoBtn.setOnClickListener(this);
        view_threeBtn=(Button)findViewById(R.id.view_threeBtn);
        view_threeBtn.setOnClickListener(this);
        view_fourBtn=(Button)findViewById(R.id.view_fourBtn);
        view_fourBtn.setOnClickListener(this);
        view_fiveBtn=(Button)findViewById(R.id.view_fiveBtn);
        view_fiveBtn.setOnClickListener(this);
        view_sixBtn=(Button)findViewById(R.id.view_sixBtn);
        view_sixBtn.setOnClickListener(this);
        view_sevenBtn=(Button)findViewById(R.id.view_sevenBtn);
        view_sevenBtn.setOnClickListener(this);
        view_eightBtn=(Button)findViewById(R.id.view_eightBtn);
        view_eightBtn.setOnClickListener(this);
        view_nineBtn=(Button)findViewById(R.id.view_nineBtn);
        view_nineBtn.setOnClickListener(this);
        view_zeroBtn=(Button)findViewById(R.id.view_zeroBtn);
        view_zeroBtn.setOnClickListener(this);
        view_pointBtn=(Button)findViewById(R.id.view_pointBtn);
        view_pointBtn.setOnClickListener(this);
        view_delBtn=(Button)findViewById(R.id.view_delBtn);
        view_delBtn.setOnClickListener(this);
        view_clrBtn=(Button)findViewById(R.id.view_clrBtn);
        view_clrBtn.setOnClickListener(this);
        findViewById(R.id.btn_Close).setOnClickListener(this);
        System.out.println("ViewFragment..............................5");
        //初始提醒;
        curToast = Toast.makeText(this, getString(R.string.SystemHint), Toast.LENGTH_LONG);
        view_rtpStyleNoText.setText(curRptStyleNo);
        view_styleNoText.setText(curStyleNo);
        view_styleSortText.setText(curStyleSort);
    }


    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.btn_checkData:

                AlertDialog alertDialog = new AlertDialog.Builder(this)
                        .setTitle(getString(R.string.SystemHint)).setMessage("")
                        .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        }).create();
                if (CheckDaliyCount()==false){
                    alertDialog.setMessage("数据检查未通过，目标总积分需与报帐总积分相同!");
                } else alertDialog.setMessage("数据检查通过!");
                alertDialog.show(); // 显示对话框
                break;
            case R.id.btn_viewRefresh:
                refreshProcListFromCSP(curDepartNo,curKeyID,curOrderNo,curRptStyleNo,curStyleNo,curStyleSort,curLoginUserNo);
                break;
            case R.id.view_oneBtn:
            case R.id.view_twoBtn:
            case R.id.view_threeBtn:
            case R.id.view_fourBtn:
            case R.id.view_fiveBtn:
            case R.id.view_sixBtn:
            case R.id.view_sevenBtn:
            case R.id.view_eightBtn:
            case R.id.view_nineBtn:
            case R.id.view_zeroBtn:
                Button tmpBtn1=(Button)v.findViewById(v.getId());
                if (overWriteSign==true) {
                    view_numEdit.setText(tmpBtn1.getText());
                    overWriteSign=false;
                } else view_numEdit.getText().append(tmpBtn1.getText());
                if (view_numEdit.getText().toString().length()>0) updateNumber(Float.parseFloat(view_numEdit.getText().toString()));
                else  updateNumber(0);
                break;
            case R.id.view_delBtn:
                if (view_numEdit.getText().length()>0)
                {
                    overWriteSign=false;
                    view_numEdit.setSelection(view_numEdit.getText().length());
                    System.out.println(view_numEdit.getSelectionStart());
                    int start=view_numEdit.getSelectionStart();
                    view_numEdit.getText().delete(start-1,start);
                }
                if (view_numEdit.getText().toString().length()>0) updateNumber(Float.parseFloat(view_numEdit.getText().toString()));
                else  updateNumber(0);
                break;
            case R.id.view_pointBtn:
                System.out.println("AindexOf:" + view_numEdit.getText().toString().indexOf("."));
                if ((view_numEdit.getText().toString().indexOf(".") == -1)&&(view_numEdit.getText().toString().indexOf("/") == -1)) {
                    view_numEdit.getText().append(".");
                }
                break;
            case R.id.btn_affirmData:
            case R.id.btn_saveData:
                if (AllowAffirm.equals("N")){
                    AlertDialog alertDialog1 = new AlertDialog.Builder(this)
                            .setTitle(getString(R.string.SystemHint)).setMessage("不允许积分确认!")
                            .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            }).create();
                    alertDialog1.show(); // 显示对话框t
                    return;
                }
                //调用存储过程刷新数据;
                if (CheckDaliyCount()==false){
                    AlertDialog alertDialog1 = new AlertDialog.Builder(this)
                            .setTitle(getString(R.string.SystemHint)).setMessage("数据检查未通过，报帐总积分需小于目标总积分!")
                            .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            }).create();
                    alertDialog1.show(); // 显示对话框t
                }else{
                    if (v.getId()==R.id.btn_affirmData)
                        saveData(curDepart,curKeyID,curOrderNo,curRptStyleNo,curStyleNo,curStyleSort,"Affirm");
                    else
                        saveData(curDepart,curKeyID,curOrderNo,curRptStyleNo,curStyleNo,curStyleSort,"Save");
                }
                break;
            case R.id.view_clrBtn:
                view_numEdit.setText("");
                updateNumber(0);
                break;
            case R.id.btn_Close:
                AlertDialog alertDialog2 = new AlertDialog.Builder(v.getContext())
                        .setTitle("系统提示").setMessage("你确定要关闭当前窗口？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                //返回
                                Intent intent = new Intent();
                                intent.putExtra("CurKeyID",curKeyID);
                                intent.putExtra("AllowAffirm",AllowAffirm);
                                setResult(1001,intent);
                                finish();
                            }
                        }).setNeutralButton("取消",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        return;
                                    }
                                }).create(); // 创建对话框
                alertDialog2.show(); // 显示对话框
                break;
            default:
                break;
        }
    }

    //提交所选择的工序至服务器,然后刷新工序列表;
    private void saveData(final String paramDepart,  final String paramKeyID, final String paramOrderNo, final String paramRptStyleNo, final String paramStyleNo, final String paramStyleSort,final String paramTransMethod){
        if (procJSONArray == null || procJSONArray.length()==0) return;
        Runnable run = new Runnable() {
            @Override
            public void run() {
                String SqlComm;
                String AffirmProcID = java.util.UUID.randomUUID().toString();
                //将数据读到JSONArray;
                try {
                    System.out.println("saveData:"+1);
                    PreparedStatement pstmt = DBUtil.getSQLConnection().prepareStatement(
                            "Insert into AffirmProcDe(AffirmProcDeID,AffirmProcID,WorkNo,WorkName,TargetValue,RptValue) values(newid(),?,?,?,?,?)");
                    //增加明细表
                    for (int i = 0; i < procJSONArray.length(); i++) {
                        if (procJSONArray.getJSONObject(i).has("RptValue") == true) {
                            if (procJSONArray.getJSONObject(i).getString("RptValue").length() > 0) {
                                pstmt.setString(1, AffirmProcID);
                                pstmt.setString(2, procJSONArray.getJSONObject(i).getString("WorkNo"));
                                pstmt.setString(3, procJSONArray.getJSONObject(i).getString("WorkName"));
                                pstmt.setDouble(4, procJSONArray.getJSONObject(i).getDouble("TargetValue"));
                                pstmt.setDouble(5, procJSONArray.getJSONObject(i).getDouble("RptValue"));
                                System.out.println(i+"->"+"WorkNo:"+ procJSONArray.getJSONObject(i).getString("WorkNo")+" WorkName:"+procJSONArray.getJSONObject(i).getString("WorkName")
                                        +" TargetValue:"+procJSONArray.getJSONObject(i).getString("TargetValue")+" RptValue:"+procJSONArray.getJSONObject(i).getString("RptValue"));
                                pstmt.executeUpdate();
                            }
                        }
                    }
                    pstmt.close();
                    //增加主表;
                    System.out.println("saveData:"+2+"-start");
                    pstmt = DBUtil.getSQLConnection().prepareStatement(
                            "Insert into AffirmProc(AffirmProcID,Depart,KeyID,OrderNo,RptStyleNo,StyleNO,StyleSort,UserNo,UserName,CreateTime) values(?,?,?,?,?,?,?,?,?,getdate())");
                    pstmt.setString(1, AffirmProcID);
                    pstmt.setString(2, paramDepart);
                    pstmt.setString(3, paramKeyID);
                    pstmt.setString(4, paramOrderNo);
                    pstmt.setString(5, paramRptStyleNo);
                    pstmt.setString(6, paramStyleNo);
                    pstmt.setString(7, paramStyleSort);
                    pstmt.setString(8, curLoginUserNo);
                    pstmt.setString(9, curLoginUser);
                    pstmt.executeUpdate();
                    pstmt.close();
                    System.out.println("saveData:"+2+"-end");
                    System.out.println();
                    //调用存储过程;
                    /*
                    SqlComm = " Exec ScenePAD_AffirmProcSaveTrans @OperType='SaveTrans',@FormType='AffirmProc',@TransMethod='"+paramTransMethod+"',@AffirmProcID='" + AffirmProcID + "'";
                    System.out.println("saveData:"+3+"->SqlComm:"+SqlComm);

                    ReadSQLData(SqlComm);
                     */
                    // 使用GET方法发送请求,需要把参数加在URL后面，用？连接，参数之间用&分隔
                    String url = CSP_URL + "/bbzx/ScenePAD/AffirmProcSaveTrans?operType=SaveTrans&formType=AffirmProc&transMethod=" + paramTransMethod + "&affirmProcID=" + AffirmProcID;
                    System.out.println(url);
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpGet httpGet = new HttpGet(url);
                    // 发送请求
                    try {
                        HttpResponse httpResponse = httpClient.execute(httpGet);
                        if (httpResponse.getStatusLine().getStatusCode() == 200) {
                            HttpEntity entity = httpResponse.getEntity();
                            String jsonStr = EntityUtils.toString(entity, "utf-8");
                            System.out.println("jsonStr:"+jsonStr);
                            JSONObject jsonObject = new JSONObject(jsonStr);
                            if (jsonObject.has("data")) {
                                Log.d("msg","MSG_SaveTransOver--------------------2");
                                JSONObject tmpObject=new JSONObject();
                                if (jsonObject.has("AllowAffirm")) tmpObject.put("AllowAffirm",jsonObject.getString("AllowAffirm"));
                                if (jsonObject.has("msg")) tmpObject.put("ResultInfo",jsonObject.getString("msg"));
                                resultJson=new JSONArray();
                                resultJson.put(tmpObject);
                                //显示预排单;
                                Message msg = new Message();
                                msg.what = MSG_SaveTransOver;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            } else {
                                //关闭ProgressDialog
                                Message msg = new Message();
                                msg.what = MSG_ERRMSG;
                                Bundle bundle=new Bundle();
                                bundle.putString("MSG","请求接口出错");
                                msg.setData(bundle);
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }

                        } else {
                            //关闭ProgressDialog
                            Message msg = new Message();
                            msg.what = MSG_ERRMSG;
                            Bundle bundle=new Bundle();
                            bundle.putString("MSG","未返回任何内容");
                            msg.setData(bundle);
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                        //关闭ProgressDialog
                        Message msg = new Message();
                        msg.what = MSG_ERRMSG;
                        Bundle bundle=new Bundle();
                        bundle.putString("MSG",e.getMessage());
                        msg.setData(bundle);
                        fragmentHandler.removeMessages(msg.what);
                        fragmentHandler.sendMessage(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
        };
        new Thread(run).start();
    }

    private void updateNumber(float paramNumber){
        if (selRowIndex>=0){
            if (procJSONArray !=null)
            {
                try {
                    dataEditSign=true;
                    procJSONArray.getJSONObject(selRowIndex).put("RptValue",paramNumber);
                    //更新显示;
                    ((BaseAdapter) procList.getAdapter()).notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                UpdateTotal();
            }
        }

    }

    //刷新工序列表;
    private void refreshProcList(final String paramDepart,  final String paramKeyID, final String paramOrderNo, final String paramRptStyleNo,
                                 final String paramStyleNo, final String paramStyleSort,final String paramUserNo)
    {
        selRowIndex = -1;
        waitDialog.setMessage(getString(R.string.WaitingFromNetGetData));
        //执行SQL过程
        String SqlComm = "Exec ScenePAD_AffirmGetProc  @OperType='GetProc',@DepartmentNo='" + paramDepart+ "',@KeyID='" + paramKeyID  + "',@OrderNo='" + paramOrderNo
                + "',@RptStyleNo='" + paramRptStyleNo+ "',@StyleNo='" + paramStyleNo + "',@StyleSort='" + paramStyleSort + "',@UserNo='" + paramUserNo + "',@WorkSection='" + WorkSection + "'";
        //调用WebService过程并处理界面更新;
        Log.d("msg", "serviceUrl------------------" + serviceUrl);
        ReadSQLData(SqlComm);
    }

    //从CSP查询数据
    private void refreshProcListFromCSP(final String paramDepart,  final String paramKeyID, final String paramOrderNo, final String paramRptStyleNo,
                                 final String paramStyleNo, final String paramStyleSort,final String paramUserNo){
        selRowIndex = -1;
        waitDialog.setMessage(getString(R.string.WaitingFromNetGetData));
        new Thread() {
            @Override
            public void run() {
                super.run();
                // 使用GET方法发送请求,需要把参数加在URL后面，用？连接，参数之间用&分隔
                String url = CSP_URL + "/bbzx/ScenePAD/AffirmGetProc?operType=GetProc&departmentNo=" + paramDepart + "&keyID=" + paramKeyID + "&orderNo=" + paramOrderNo + "&rptStyleNo=" + paramRptStyleNo
                        + "&styleNo=" + paramStyleNo+ "&styleSort=" + paramStyleSort+ "&userNo=" + paramUserNo;
                System.out.println(url);
                HttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(url);
                // 发送请求
                try {
                    HttpResponse httpResponse = httpClient.execute(httpGet);
                    if (httpResponse.getStatusLine().getStatusCode() == 200) {
                        HttpEntity entity = httpResponse.getEntity();
                        String jsonStr = EntityUtils.toString(entity, "utf-8");
                        System.out.println("jsonStr:"+jsonStr);
                        JSONObject jsonObject = new JSONObject(jsonStr);
                        if (jsonObject.has("data")) {
                            procJSONArray = new JSONArray(jsonObject.getString("data"));
                            System.out.println("procJSONArray:"+procJSONArray);
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_GetProcOver;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        } else {
                            //显示预排单;
                            //关闭ProgressDialog
                            Message msg = new Message();
                            msg.what = MSG_ERRMSG;
                            Bundle bundle=new Bundle();
                            bundle.putString("MSG","未返回任何内容");
                            msg.setData(bundle);
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }


    //检查数据,报数不能超过今日检验数
    private boolean CheckDaliyCount() {
        int result=0;
        if (procJSONArray == null) return false;
        if (procJSONArray.length() > 0) {
            float targetValue=0,rptValue=0;
            for (int i=0;i<procJSONArray.length();i++){
                try {
                    targetValue= (float) (targetValue+procJSONArray.optJSONObject(i).getDouble("TargetValue"));
                    rptValue= (float) (rptValue+procJSONArray.optJSONObject(i).getDouble("RptValue"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("targetValue:"+targetValue+"-reservedprice:"+reservedprice+"-rptValue:"+rptValue);
            System.out.println("targetValue-reservedprice:"+(targetValue-reservedprice));
            System.out.println("(Math.round(targetValue*10000)/10000.0):"+(Math.round(targetValue*10000)/10000));
            System.out.println("(Math.round(rptValue*10000)/10000.0):"+(Math.round(rptValue*10000)/10000));
            return (Math.round(targetValue*10000)/10000)-reservedprice>=(Math.round(rptValue*10000)/10000);
        }
        return false;

    }

    private boolean UpdateTotal() {
        int result=0;
        float SAMValue=0,TargetValue=0,RptValue=0,NotNormal=0;
        System.out.println("UpdateTotal()--1");
        if (procJSONArray == null) return false;
        System.out.println("UpdateTotal()--2");
        if (procJSONArray.length() > 0) {
            for (int i=0;i<procJSONArray.length();i++){
                try {
                    SAMValue= (float) (SAMValue+procJSONArray.optJSONObject(i).getDouble("SAMValue"));
                    TargetValue= (float) (TargetValue+procJSONArray.optJSONObject(i).getDouble("TargetValue"));
                    RptValue= (float) (RptValue+procJSONArray.optJSONObject(i).getDouble("RptValue"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("UpdateTotal()--3"+SAMValue+":"+TargetValue+":"+RptValue);
            text_WorkName.setText("共 "+procJSONArray.length()+" 道工序");
            text_SAMValue.setText(String.format("%.4f", SAMValue));
            text_TargetValue.setText(String.format("%.4f", TargetValue));
            text_RptValue.setText(String.format("%.4f", RptValue));

        }
        return false;

    }

    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        System.out.println(SQLComm);
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try{
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    String OperType="";
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)){
                        if (jsonArray.optJSONObject(0).has("OperType")==true)  OperType=jsonArray.optJSONObject(0).getString("OperType");
                        if (jsonArray.optJSONObject(0).has("OPERTYPE")==true)  OperType=jsonArray.optJSONObject(0).getString("OPERTYPE");

                        //返回的为状态数据;
                        if (OperType.equals("GetProc"))
                        {
                            //关闭ProgressDialog
                            waitDialog.hide();
                            Log.d("msg","GetDaliyCount--------------------2");
                            procJSONArray =jsonArray;
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_GetProcOver;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (OperType.equals("SaveTrans"))
                        {
                            //关闭ProgressDialog
                            waitDialog.hide();
                            Log.d("msg","MSG_SaveTransOver--------------------2");
                            resultJson =jsonArray;
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_SaveTransOver;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }

                        if (jsonArray.optJSONObject(0).has("ErrInfo")==true)
                        {
                            //关闭ProgressDialog
                            Message msg = new Message();
                            msg.what = MSG_ERRMSG;
                            Bundle bundle=new Bundle();
                            bundle.putString("MSG",jsonArray.optJSONObject(0).getString("ErrInfo"));
                            msg.setData(bundle);
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                            return;
                        }
                        //SQL异常;
                        if (jsonArray.optJSONObject(0).has("SQLExcept")==true)  {
                            //关闭ProgressDialog
                            Message msg = new Message();
                            msg.what = MSG_ERRMSG;
                            Bundle bundle=new Bundle();
                            bundle.putString("MSG",jsonArray.optJSONObject(0).getString("SQLMessage"));
                            msg.setData(bundle);
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                            return;
                        }

                    } else{
                        //关闭ProgressDialog
                        Message msg = new Message();
                        msg.what = MSG_ERRMSG;
                        Bundle bundle=new Bundle();
                        bundle.putString("MSG","未返回数据");
                        msg.setData(bundle);
                        fragmentHandler.removeMessages(msg.what);
                        fragmentHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //关闭ProgressDialog
                    Message msg = new Message();
                    msg.what = MSG_ERRMSG;
                    Bundle bundle=new Bundle();
                    bundle.putString("MSG",e.getMessage());
                    msg.setData(bundle);
                    fragmentHandler.removeMessages(msg.what);
                    fragmentHandler.sendMessage(msg);
                }
            }

        };
        new Thread(run).start();

    }


    /**
     * 定义一个Handler用于接收Fragment发出来的指令
     */
    public Handler fragmentHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg!=null){
                //消息处理;
                System.out.println("收到的消息是："+msg.what);
                //关闭ProgressDialog
                if (waitDialog.isShowing()) waitDialog.hide();
                int msgId = msg.what;
                switch (msgId) {
                    case MSG_GetProcOver:
                        UpdateTotal();
                        dataEditSign=false;
                        ProcListAdapter procListAdapter=new ProcListAdapter(procList.getContext());
                        procList.setAdapter(procListAdapter);
                        break;
                    case MSG_SaveTransOver:
                        if (resultJson!=null&&resultJson.length()>0){
                            if (resultJson.optJSONObject(0).has("AllowAffirm")){
                                try {
                                    AllowAffirm=resultJson.optJSONObject(0).getString("AllowAffirm");
                                    if (AllowAffirm.equals("N")) {
                                        findViewById(R.id.btn_affirmData).setVisibility(GONE);
                                        findViewById(R.id.btn_saveData).setVisibility(GONE);
                                        findViewById(R.id.btn_checkData).setVisibility(GONE);
                                        findViewById(R.id.linearEditNum).setVisibility(GONE);
                                    } else{
                                        findViewById(R.id.btn_affirmData).setVisibility(View.VISIBLE);
                                        findViewById(R.id.btn_saveData).setVisibility(View.VISIBLE);
                                        findViewById(R.id.btn_checkData).setVisibility(View.VISIBLE);
                                        findViewById(R.id.linearEditNum).setVisibility(View.VISIBLE);
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                            AlertDialog alertDialog = new AlertDialog.Builder(procList.getContext()).
                                    setTitle(getString(R.string.SystemHint)).
                                    setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                        }
                                    }).create();
                            if (resultJson.optJSONObject(0).has("ResultInfo")) {
                                try {
                                    alertDialog.setMessage(resultJson.optJSONObject(0).getString("ResultInfo"));
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            } else alertDialog.setMessage("保存成功！");
                            alertDialog.show(); // 显示对话框
                        }
                        break;
                    case MSG_ERRMSG:
                        Bundle bundle=msg.getData();
                        curToast.setText(bundle.getString("MSG"));
                        curToast.show();
                        break;
                    default:
                        break;
                }
            }
        }
    };


    //员工状态表格适配器;
    public final class ProcListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public ProcListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return procJSONArray.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return procJSONArray.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View  conView = inflater.inflate(R.layout.activity_affirmde_item, null, false);
            int pullVatListWidth=parent.getWidth();
            int pullVatListHeight=parent.getHeight();
            conView.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,(pullVatListHeight/15)));
            int textColor=getResources().getColor(R.color.text_black);
            try {
                Log.d("msg","ProcListAdapter-getView()----------------------------------------------------->"+position);
                if (procJSONArray.optJSONObject(position).has("ConColor")){
                    textColor=GetColorValue(procJSONArray.optJSONObject(position).getString("ConColor"));
                }

                TextView tv = (TextView) conView.findViewById(R.id.text_view_WorkNo);// 显示文字
                if (procJSONArray.optJSONObject(position).has("WorkNo"))
                    tv.setText(procJSONArray.optJSONObject(position).get("WorkNo").toString());
                tv.setTextColor(textColor);
                Log.d("msg","ProcListAdapter-getView()---1->"+position);
                tv = (TextView) conView.findViewById(R.id.text_view_WorkName);// 显示文字
                if (procJSONArray.optJSONObject(position).has("WorkName"))
                    tv.setText(procJSONArray.optJSONObject(position).get("WorkName").toString());
                tv.setTextColor(Color.BLUE);
                tv = (TextView) conView.findViewById(R.id.text_view_SAMValue);// 显示文字
                tv.setTextColor(textColor);
                if (procJSONArray.optJSONObject(position).has("SAMValue"))
                    tv.setText(String.format("%.4f", procJSONArray.optJSONObject(position).getDouble("SAMValue")));
                tv = (TextView) conView.findViewById(R.id.text_view_TargetValue);// 显示文字
                tv.setTextColor(textColor);
                Log.d("msg","ProcListAdapter-getView()---2->"+position);
                if (procJSONArray.optJSONObject(position).has("TargetValue"))
                    tv.setText(String.format("%.4f", procJSONArray.optJSONObject(position).getDouble("TargetValue")));
                tv = (TextView) conView.findViewById(R.id.text_view_RptValue);// 显示文字
                tv.setTextColor(textColor);
                Log.d("msg","ProcListAdapter-getView()---2.1->"+position);
                if (procJSONArray.optJSONObject(position).has("RptValue"))
                    tv.setText(String.format("%.4f", procJSONArray.optJSONObject(position).getDouble("RptValue")));
                Log.d("msg","ProcListAdapter-getView()---2.2->"+position);
                if ((procJSONArray.optJSONObject(position).has("RptValue"))&&(procJSONArray.optJSONObject(position).has("TargetValue"))){
                    if (!procJSONArray.optJSONObject(position).getString("RptValue").equals(procJSONArray.optJSONObject(position).getString("TargetValue")))
                        tv.setBackgroundColor(getResources().getColor(R.color.greenyellow));
                }
                tv = (TextView) conView.findViewById(R.id.text_view_TargetEffice);// 显示文字
                tv.setTextColor(textColor);
                Log.d("msg","ProcListAdapter-getView()---2.3->"+position);
                if (procJSONArray.optJSONObject(position).has("TargetEffice"))
                    tv.setText(procJSONArray.optJSONObject(position).get("TargetEffice").toString());
                tv = (TextView) conView.findViewById(R.id.text_view_RealEffice);// 显示文字
                tv.setTextColor(textColor);
                Log.d("msg","ProcListAdapter-getView()---3->"+position);
                if (procJSONArray.optJSONObject(position).has("RealEffice"))
                    tv.setText(procJSONArray.optJSONObject(position).get("RealEffice").toString());
                if (procJSONArray.optJSONObject(position).has("NotNormal")) {
                    ImageView img = (ImageView) conView.findViewById(R.id.img_NotNormal);// 显示文字
                    if (procJSONArray.optJSONObject(position).getString("NotNormal").equals("Y")){
                        img.setImageDrawable(getResources().getDrawable(R.mipmap.checkbox_button));
                    } else{
                        img.setImageDrawable(getResources().getDrawable(R.mipmap.checkbox_button_no));
                    }
                }
                Log.d("msg","ProcListAdapter-getView()---4->"+position);
            } catch (JSONException e) {
                e.printStackTrace();
                curToast.setText(e.getMessage());
                curToast.show();
            }
            Log.d("msg","OrderGridAdapter_position:"+position);
            return conView;
        }
    }

    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor= Color.WHITE;
        String StrPenColor=paramColor;
        if ((StrPenColor.indexOf("#")==0)&&(StrPenColor.length()==7)){
            int testColor=Integer.parseInt(StrPenColor.substring(1),16);
            int red = (testColor & 0xff0000) >> 16;
            int green = (testColor & 0x00ff00) >> 8;
            int blue = (testColor & 0x0000ff);
            PenColor=Color.rgb(red, green, blue);
        }else {
            if (isNumer(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
            }
        }
        return PenColor;
    }

    //判断是否为数字
    public static boolean isNumer(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

}
